﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using mitasoft.Component.Models;
using mitasoft.Component.Services;
using StructureMap;
using mitasoft.Component.Services.Interfaces;
using mitasoft.Component.Enums;

namespace mitasoft.Component.Helpers {

    public static class CacheHelper {

        /// <summary>
        /// Get site setting
        /// </summary>
        public static string RetriveSiteSetting(SiteSettingsCacheKeysEnum key) {
            
            return SiteSettingsCache()
                .Where(x => x.Parameter.Equals(key.ToString()))
                .Select(x => x.Value)
                .FirstOrDefault();
        }

        #region private methods

        /// <summary>
        /// SiteSettingsCache collection
        /// </summary>
        private static IEnumerable<SiteSettings> SiteSettingsCache() {

            var siteSettings = GetFromAppCache<IEnumerable<SiteSettings>>(AppCacheKeysEnum.SiteSettings);
            if (siteSettings == null) {

                var commonService = ObjectFactory.GetInstance<ICommonService>();
                siteSettings = commonService.RetriveSiteSettings();

                SetAppCache(AppCacheKeysEnum.SiteSettings, siteSettings);
            }

            return siteSettings;
        }

        /// <summary>
        /// put object in cache
        /// </summary>
        private static void SetAppCache(AppCacheKeysEnum key, dynamic obj) {
            HttpContext.Current.Application.Lock();
            HttpContext.Current.Application[key.ToString()] = obj;
            HttpContext.Current.Application.UnLock();
        }

        /// <summary>
        /// get object from cache
        /// </summary>
        private static T GetFromAppCache<T>(AppCacheKeysEnum key) {

            var result = (T)HttpContext.Current.Application[key.ToString()];
            return result;
        } 
        #endregion
    }

   
  
}
